#!/usr/bin/env python3
"""
创建测试用户脚本（简化版）
用户名: admin
密码: admin
"""

import asyncio
import asyncpg
from passlib.context import CryptContext

# 密码加密
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

async def create_test_user():
    """创建测试用户"""
    
    # 连接数据库
    try:
        conn = await asyncpg.connect(
            host="localhost",
            port=5432,
            user="postgres",
            password="postgres",
            database="ai_writing_db"
        )
    except Exception as e:
        print(f"数据库连接失败: {e}")
        print("\n尝试使用默认数据库...")
        conn = await asyncpg.connect(
            host="localhost",
            port=5432,
            user="postgres",
            password="postgres",
            database="postgres"
        )
        
        # 创建数据库
        await conn.execute("CREATE DATABASE ai_writing_db")
        await conn.close()
        
        # 重新连接
        conn = await asyncpg.connect(
            host="localhost",
            port=5432,
            user="postgres",
            password="postgres",
            database="ai_writing_db"
        )
    
    try:
        # 创建用户表（如果不存在）
        await conn.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id SERIAL PRIMARY KEY,
                username VARCHAR(50) UNIQUE NOT NULL,
                email VARCHAR(100) UNIQUE NOT NULL,
                password_hash VARCHAR(200) NOT NULL,
                is_active BOOLEAN DEFAULT true,
                is_superuser BOOLEAN DEFAULT false,
                created_at TIMESTAMP DEFAULT NOW(),
                updated_at TIMESTAMP DEFAULT NOW()
            )
        """)
        
        # 检查用户是否已存在
        existing_user = await conn.fetchrow(
            "SELECT id FROM users WHERE username = $1 OR email = $2",
            "admin", "admin@example.com"
        )
        
        hashed_password = pwd_context.hash("admin")
        
        if existing_user:
            # 更新现有用户
            await conn.execute(
                """
                UPDATE users 
                SET password_hash = $1, 
                    username = $2,
                    email = $3,
                    is_active = true,
                    is_superuser = true,
                    updated_at = NOW()
                WHERE username = $2 OR email = $3
                """,
                hashed_password, "admin", "admin@example.com"
            )
            print("✅ 测试用户已更新")
        else:
            # 创建新用户
            await conn.execute(
                """
                INSERT INTO users (
                    username, 
                    email, 
                    password_hash, 
                    is_active, 
                    is_superuser
                ) VALUES ($1, $2, $3, $4, $5)
                """,
                "admin", 
                "admin@example.com", 
                hashed_password, 
                True, 
                True
            )
            print("✅ 测试用户创建成功")
            
        print("\n📝 登录信息:")
        print("=" * 30)
        print("用户名: admin")
        print("邮箱: admin@example.com")
        print("密码: admin")
        print("=" * 30)
        print("\n💡 提示: 可以使用用户名或邮箱登录")
        
    except Exception as e:
        print(f"❌ 错误: {e}")
    finally:
        await conn.close()

if __name__ == "__main__":
    print("🚀 开始创建测试用户...")
    asyncio.run(create_test_user())